package wjio;

import java.io.*;
import java.util.Scanner;

public class demo15_0527 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径: ");
        String rootPath = scanner.next();
        System.out.println("请输入要查询的词: ");
        String word = scanner.next();

        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("输入的要搜索的路径不正确!");
            return;
        }

        scanDir(rootFile, word);
    }
    public static void scanDir(File rootfile, String word) {
        File[] files = rootfile.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            System.out.println("【debug】当前遍历到了" + f.getAbsoluteFile());
            if (f.isFile()) {
                searchInFile(f,word);
            } else if (f.isDirectory()) {
                scanDir(f,word);
            } else {

            }
        }
    }

    private static void searchInFile(File f, String word) {
        try (InputStream inputStream = new FileInputStream(f)){
            StringBuffer stringBuffer = new StringBuffer();
            while (true) {
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if (n == -1) {
                    break;
                }
                String s = new String(buffer,0,n);
                stringBuffer.append(s);
            }
            System.out.println("[debug] 文件内容: " + stringBuffer);
            if (stringBuffer.indexOf(word) == -1) {
                return;
            }
            System.out.println("找到了" + word + "：" + f.getAbsoluteFile());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
